package com.ling.luo.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ling.luo.user.entity.User;
import com.ling.luo.user.mapper.UserMapper;
import com.ling.luo.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Objects;

/**
 * 用户类 service 层
 *
 * @author luohoujian01
 * @since 2020/12/01
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 通过 userId 查询 User
     * @param id
     * @return
     */
    @Override
    @Cacheable(value = "user_details", key = "#id", unless = "#result == null")
    public User getByUserId(String id) {
        if (StringUtils.isEmpty(id)) {
            throw new RuntimeException("id 为空");
        }
        return userMapper.selectById(id);
    }

    /**
     * 更新用户
     * @param user
     * @return
     */
    @Override
    @CachePut(value = "user_details", key = "#user.id")
    @Transactional(rollbackFor = RuntimeException.class)
    public User updateUser(User user) {
        User oldUser = userMapper.selectById(user.getId());
        if (Objects.isNull(oldUser)) {
            throw new RuntimeException("该用户不存在");
        }
        userMapper.updateById(user);
        return user;
    }

    /**
     * 通过id删除用户
     * @param id
     */
    @Override
    @CacheEvict(value = "user_details", key = "#id")
    public void deleteById(String id) {
        userMapper.deleteById(id);
    }
}
